package com.espoir.shp.read01;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.nio.charset.Charset;
import java.util.*;

public class ShapeReader {
    public ArrayList<ShapeModel> readShapeFile(String filePath) {
        ArrayList<ShapeModel> modelList = new ArrayList<>();
        File folder = new File(filePath);
        if (!folder.isDirectory()) {
            if (folder.toString().endsWith(".shp")) {
                try {
                    modelList = getShapeFile(folder);
                    return modelList;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("选择的文件后缀名不是.shp");
            }
        } else {
            File[] files = folder.listFiles();
            if (!(files.length > 0)) {
                System.out.println("目录文件为空");
                return modelList;
            }

            for (File file : files) {
                if (!file.toString().endsWith(".shp")) {
                    continue;
                }
                try {
                    ArrayList<ShapeModel> models = getShapeFile(file);
                    modelList.addAll(models);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return modelList;
    }

    private ArrayList<ShapeModel> getShapeFile(File file) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", file.toURI().toURL());
        ArrayList<ShapeModel> models = new ArrayList<>();
        DataStore dataStore = DataStoreFinder.getDataStore(map);
        //字符转码，防止中文乱码
        //((ShapefileDataStore) dataStore).setCharset(Charset.forName("utf8"));
        ((ShapefileDataStore) dataStore).setCharset(Charset.forName("gbk"));

        // typeName 指的是 shapefile 的文件名
        String typeName = dataStore.getTypeNames()[0];

        //
        FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);
        FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();

        // 所有要素的迭代器
        FeatureIterator<SimpleFeature> features = collection.features();

        /**
         * features 就代表一个 shapefile
         * 一个 feature 代表一个要素，也就一代表 shapefile 中的一行记录
         * 或者说一个特征点，特征面，
         * */
        while (features.hasNext()) {
            System.out.println("features = " + features);
            SimpleFeature feature = features.next();
            ShapeModel model = new ShapeModel();
            Iterator<? extends Property> iterator = feature.getValue().iterator();
            System.out.println(" 一行记录开始0------------------------");
            /**
             * shapefile 中的字段 FID 和 shape 字段不能读取
             *
             * shapefile 中 the_geom 字段每条记录中存储的 geometry 信息，是 shapefile 默认的，无法修改
             *
             * */
            while (iterator.hasNext()) {
                /**
                 * property 代表一个属性，也就 shapefile 中的一个字段
                 *
                 * */
                Property property = iterator.next();
                String propertyName = property.getName().toString();
                String propertyValue = property.getValue().toString();
                //System.out.println("propertyName = " + propertyName +" propertyValue : "+propertyValue);
                //property数据与实体类对应
                if (propertyName.equals("NAME")) {
                    model.setName(propertyValue);
                }
                if (propertyName.equals("KIND")) {
                    model.setKind(propertyValue);
                }
                if (propertyName.equals("the_geom"))
                    model.setGeoStr(propertyValue);
                if (propertyName.equals("Shape"))
                    System.out.println("shape = " + property.getValue().toString());
                if (propertyName.equals("layer"))
                    model.setLayer(property.getValue().toString());
                if (propertyName.equals("projection"))
                    model.setProjection(propertyValue);
                if (propertyName.equals("region"))
                    model.setRegion(propertyValue);
                if (propertyName.equals("regionCode"))
                    model.setRegionCode(propertyValue);
                if (propertyName.equals("level"))
                    model.setLevel(Integer.parseInt(propertyValue));
                if (propertyName.equals("time"))
                    model.setTime(propertyValue);
                model.setCreateTime(new Date());
                model.setClazz("");

            }
            models.add(model);
        }
        return models;
    }
}
